﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Windows.Forms;
using HF_ReaderLib;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using YunLib.HF.HF;

namespace YunLib.HF
{
    public partial class Form1 : Form
    {
        private string SIP = ConfigurationManager.AppSettings["IP"];
        private string SPort = ConfigurationManager.AppSettings["PORT"];
        private string COM = ConfigurationManager.AppSettings["COM"];
        private string Baud = ConfigurationManager.AppSettings["BAUD"];

        HF_readerlib HF_Reader = new HF_readerlib();
        Thread ThreadByUID;
        bool Running = false;
        private delegate void ClearListView();
        private delegate void DataBind(List<string> UID, List<string> DSFID, List<string> Manufacturer, List<string> AntennaID);
        private List<string> uid = new List<string>();
        private List<string> dsfid = new List<string>();
        private List<string> manufacturer = new List<string>();
        private List<string> antennaid = new List<string>();
        private string ANT_NUMBER = null;
        Socket socket;
        byte[] bytes = new byte[4096];

        private volatile bool _shouldStop;
        private volatile List<DataTag> TagsList = new List<DataTag>();
        public Form1()
        {
            InitializeComponent();
            //ThreadByUID = new Thread(new ThreadStart(GetByUID));
            //ThreadByUID.IsBackground = true;
            //ThreadByUID.Start();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(SIP), int.Parse(SPort));

            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            socket.Blocking = true;
            try
            {
                socket.Connect(ipep);
                // richTextBox1.AppendText("链接成功\r\n");
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.Message);
            }

            int result = HF_Reader.OpenPort(COM, Int32.Parse(Baud));
            if(result == 0)
            {
                MessageBox.Show("串口打开成功");
                Running = true;
            }
            else
            {
                MessageBox.Show("串口打开失败");
            }
           

        }

        #region Socket
        protected string threadFunc(string sendMsg)
        {
            try
            {
                byte[] msg;
                string bytesRec;
                // msg = Encoding.UTF8.GetBytes(str);
                //str = "11NN20180622    11115020180622    111150AO|AA660000000031|AB51082300015143|AC|CN001|AY1AZEC5C  " + Environment.NewLine;

                byte[] buffer = Encoding.UTF8.GetBytes(sendMsg);



                socket.Send(buffer);
                socket.Receive((bytes));
                bytesRec = Encoding.UTF8.GetString(bytes);

                string ab = "";
                string aj = "";
                List<string> li = Exstring(bytesRec);
                for (int i = 0; i < li.Count; i++)
                {
                    if (li[i].Length > 2)
                    {
                        if (li[i].Substring(0, 2) == "AB")
                        {
                            ab = li[i].Substring(2);
                        }
                        else if (li[i].Substring(0, 2) == "AJ")
                        {
                            aj = li[i].Substring(2);
                        }

                    }
                }

                return aj;


                //string ret;
                //SetLog("获取的数据是" + bytesRec + "\r\n");
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
                return "";
            }

        }



        /// <summary> 把命令解析成一个个单个信息存贮在list<>里 </summary> <param name="st"></param> <returns></returns>
        public List<string> Exstring(string st)
        {
            var li = new List<string>();

            string[] arr = st.Split('|');
            for (int i = 0; i < arr.Length; i++)
            {
                li.Add(arr[i]);
            }

            return li;
        }


        delegate void SetLogCallBack(string log);
        /// <summary>
        /// 更新richtextbox控件的具体方法
        /// </summary>
        /// <param name="str">传入的字符串</param>
        private void SetLog(string str)
        {
            //if (this.richTextBox1.InvokeRequired)
            //{
            //    SetLogCallBack d = new SetLogCallBack(SetLog);
            //    this.Invoke(d, new object[] { str });
            //}
            //else
            //    this.richTextBox1.AppendText(str);

        }
        #endregion

        #region HF读卡
        private void GetByUID()
        {
            DateTime start = DateTime.Now;
            for(int i = 0; i < numericUpDown1.Value; i++) { 
               
                if (Running)
                {
                    List<string> Temp_uid = new List<string>();
                    List<string> Temp_dsfid = new List<string>();
                    List<string> Temp_manufacturer = new List<string>();
                    List<string> Temp_antennaid = new List<string>();
                  //  DataBind Bind_ListView = new DataBind(BindByListView);
                    int ANT = 255;
                    if (!string.IsNullOrEmpty(ANT_NUMBER))
                    {
                        if (ANT_NUMBER == "[ALL]")
                        {
                            ANT = 255;
                        }
                        else
                        {
                            ANT = Convert.ToInt32(ANT_NUMBER);
                        }
                    }
                    int result = HF_Reader.Inventory(4000, ANT, ref Temp_uid, ref Temp_dsfid, ref Temp_manufacturer, ref Temp_antennaid);
                    if (result == 0)
                    {
                        //赋值
                        // Invoke(Bind_ListView, Temp_uid, Temp_dsfid, Temp_manufacturer, Temp_antennaid);
                        BindByListView(Temp_uid, Temp_dsfid, Temp_manufacturer, Temp_antennaid);
                    }
                    else
                    {
                        //if (HF_Reader.BreakRec == false)
                        //{
                        //    if (!checkBox2.Checked)
                        //    {
                        //        this.Invoke(clear);
                        //    }
                        //}
                    }
                }
            }
            DateTime end = DateTime.Now;
            TimeSpan ts = end - start;
            lblTime.Text = ts.TotalSeconds.ToString()+"秒";
        }

       
        private delegate void AntennaSelection(string antid);
        void BindByListView(List<string> UID, List<string> DSFID, List<string> Manufacturer, List<string> AntennaID)
        {
          
            if (UID.Count > 0)
            {
                for (int i = 0; i < UID.Count; i++)
                {
                    int offset = 0;
                    if (-1 != (offset = tags_list_traverse(UID[i])))
                    {
                        TagsList[offset].count += 1;
                    }
                    else
                    {
                        DataTag dt = new DataTag();
                        dt.uid = UID[i];
                        dt.dsfid = DSFID[i];
                        dt.manufacturer = Manufacturer[i];
                        dt.antennaid = AntennaID[i];
                        dt.count = 1;
                        TagsList.Add(dt);

                    }
                    //    Get_AntennaNum.Invoke(AntennaID[i]);


                }
            }
        }

        private int tags_list_traverse(string uid)
        {
            for (int index = 0; index < TagsList.Count; index++)
            {
                

                if ((TagsList[index].uid == uid))
                {
                    return index;
                }
            }

            return -1;
        }

        private void search()
        {
            string barcode = "";
            string title = "";
            while (true) {
                if (DataGridViewList.RowCount > 0)
                {
                    for(int i = 0;i<TagsList.Count;i++)
                    {
                        barcode = TagsList[i].BarCode.ToString();
                        title = TagsList[i].Title.ToString();
                        if (string.IsNullOrWhiteSpace(barcode))
                        {
                            string[] test = new string[1];
                            int result = HF_Reader.ReadMultBlock(TagsList[i].uid, 1, 1, ref test);
                            if (result == 0 && test.Length > 0)
                            {
                                //   string str = BitConverter.ToString(test).Replace("-", "");
                                TagsList[i].BarCode = test[0].Substring(1);
                                string str = "1720181206    155911AO|AB" + test[0].Substring(1) + "|AC|AY4AZF618";
                                string s1 = threadFunc(str);
                                TagsList[i].Title = s1;
                            }
                        }
                        else
                        {
                            if (string.IsNullOrWhiteSpace(title))
                            {
                                string str = "1720181206    155911AO|AB" + barcode + "|AC|AY4AZF618";
                                string s1 = threadFunc(str);
                                TagsList[i].Title = s1;
                            }
                        }
                    }
                }
                
            }
        }

    
        void GetAntennaNum(string Antenid)
        {
            //if (!checkedListBox1.Items.Contains("[所有天线]"))
            //{
            //    checkedListBox1.Items.Add("[所有天线]");
            //}
            //if (!checkedListBox1.Items.Contains("Antenna#" + Antenid))
            //{
            //    checkedListBox1.Items.Add("Antenna#" + Antenid);
            //}
        }
        #endregion

        private void button1_Click(object sender, EventArgs e)
        {
            if (ThreadByUID != null)
            {
                ThreadByUID.Abort();
            }
            ThreadByUID = new Thread(new ThreadStart(search));
            ThreadByUID.IsBackground = true;
            ThreadByUID.Start();

            GetByUID();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            updata_tags_listview();
        }

        private void updata_tags_listview()
        {
            List<DataTag> tmp_tags_list = new List<DataTag>(1000);

            //lock (tags_list)
            {
                tmp_tags_list = TagsList;
            }

            for (int index = 0; index < tmp_tags_list.Count; index++)
            {
                UpdataLabel(tmp_tags_list[index], index);
            }
        }

        private void UpdataLabel(DataTag tag_item, int nIndex)
        {
           
            string[] arr = new string[8];
            arr[0] = (DataGridViewList.RowCount + 1).ToString();
            arr[1] = tag_item.uid;
            arr[2] = tag_item.dsfid;
            arr[3] = tag_item.manufacturer;
            arr[4] = tag_item.antennaid;
            arr[5] = tag_item.count + "";
            arr[6] = tag_item.BarCode;
            arr[7] = tag_item.Title;



            bool Exist = false;
            //判断标签是否被重复扫描
            //for (int iCount = 0; iCount < DataGridViewList.RowCount; iCount++)
            //{
            if (DataGridViewList.RowCount > 0)
            {
                foreach (DataGridViewRow dt in this.DataGridViewList.Rows)
                {
                    if (dt.Cells[1].Value.ToString() == tag_item.uid)
                    {
                        dt.Cells[2].Value = tag_item.dsfid;
                        dt.Cells[3].Value = tag_item.manufacturer;
                        dt.Cells[4].Value = tag_item.antennaid;
                        dt.Cells[5].Value = tag_item.count;
                        dt.Cells[6].Value = tag_item.BarCode;
                        dt.Cells[7].Value = tag_item.Title;
                        Exist = true;
                        break;
                    }

                }
            }
            //}

            if (!Exist)
            {
                DataGridViewList.Rows.Insert(DataGridViewList.RowCount, arr);
            }
        }

        private void timer2_Tick(object sender, EventArgs e)
        {
            
        }

        private void button2_Click(object sender, EventArgs e)
        {
            ThreadByUID.Abort();
            TagsList.Clear();
            //     DataGridViewList.cl
            while (this.DataGridViewList.Rows.Count != 0)
            {
                this.DataGridViewList.Rows.RemoveAt(0);
            }
            lblTime.Text = "";
        }
    }
}
